# Table G.1 
rm(list=ls())

(WD <- getwd())
if (!is.null(WD)) setwd(WD)

indata0      = paste0(WD,"/_other_data/_zew/","", collapse = NULL)

library(haven)
library(AER)
library(sandwich)
library(lmtest)
library(pracma)
library(stargazer)
library(plm)
library(pracma)
library(DataCombine)
library(jtools)
library(plyr)
library(readxl)
library(foreign)
library(DescTools)

lagpad <- function(x, k) {
  res <- c(rep(NA, k), x)[1:length(x)]
  return(res)
}

data_realz         = read_excel(paste(indata0,"real_gdp.xls",sep=""), sheet = "data")
tmp                = row(data_realz)
tmp                = tmp[,1]
data_realz$qdate   = 1991+(tmp-1)/4
data_realz         = subset(data_realz, select = c(qdate,Y))

data_zew           = read_excel(paste(indata0,"zew_data.xlsx",sep=""), sheet = "data")
tmp                = row(data_zew)
tmp                = tmp[,1]
data_zew$qdate     = data_zew$YEAR+(data_zew$MONTH-3)/12
data_zew           = subset(data_zew, select = c(qdate,zew_consensus_expectation, zew_consensus, zew))

data              = merge(data_realz, data_zew, all=TRUE)
data              = data[-4:-1,]

data$ytmp         = interp1(data$qdate,data$Y, xi = data$qdate, method = c("linear"))
data$y            = 200*(data$ytmp/lagpad(data$ytmp,6)-1)

data$zew_cons    = -data$zew_consensus
data$zew_cons_e  = -data$zew_consensus_expectation

data$error_cons  = lagpad(data$zew_cons - data$zew_cons_e,3)
data$zew_cons    = lagpad(data$zew_cons,3)

data$error_cons_wiz = Winsorize(data$error_cons, probs = c(0.05,0.95), na.rm = TRUE, type = 7)

data$fundamental    = data$zew
data$neg_consensus  = data$zew_cons

rovc.lm             = lm(error_cons_wiz ~  fundamental + neg_consensus -1, data=data)
std_error           = sqrt(diag(vcovHC(rovc.lm, type = "HC1")))

stderror = list(std_error)

stargazer(rovc.lm, 
          type = "text",
          se = stderror,
          out="_tables/table_g1.txt")
